<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>智慧养老系统</h2>
        <p>欢迎使用智慧养老管理平台</p>
      </div>
      
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" class="login-form">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-radio-group v-model="loginForm.role" class="role-group">
            <el-radio value="admin">管理员</el-radio>
            <el-radio value="user">用户</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            @click="handleLogin"
            :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="quick-login">
        <p>快速登录：</p>
        <div class="quick-login-buttons">
          <el-button 
            type="success" 
            size="small" 
            @click="quickLogin('admin')"
            :loading="loading"
          >
            管理员登录
          </el-button>
          <el-button 
            type="info" 
            size="small" 
            @click="quickLogin('user')"
            :loading="loading"
          >
            用户登录
          </el-button>
        </div>
      </div>
      
      <div class="login-tips">
        <p>测试账号：</p>
        <p>管理员 - 用户名：admin，密码：123456</p>
        <p>用户 - 用户名：user，密码：123456</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'

const router = useRouter()
const loginFormRef = ref()
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  role: 'admin'
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (valid) {
      loading.value = true
      
      try {
        // 调用后端登录API
        const response = await fetch('http://localhost:8080/api/auth/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: loginForm.username,
            password: loginForm.password
          })
        })
        
        const result = await response.json()
        
        if (result.code === 200) {
          // 登录成功
          const loginData = result.data
          
          // 存储用户信息和token
          const userInfo = {
            id: loginData.userId,
            username: loginData.username,
            role: loginData.role,
            token: loginData.token,
            loginTime: new Date().toISOString()
          }
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          localStorage.setItem('token', loginData.token)
          
          ElMessage.success('登录成功！')
          
          // 根据角色跳转到不同页面
          if (loginData.role === 'admin') {
            console.log('正在跳转到管理员页面...')
            await router.push('/admin/dashboard')
          } else {
            console.log('正在跳转到用户页面...')
            await router.push('/user/dashboard')
          }
        } else {
          ElMessage.error(result.message || '登录失败')
        }
      } catch (error) {
        console.error('登录请求失败:', error)
        ElMessage.error('网络连接失败，请检查后端服务是否启动')
      }
      
      loading.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    loading.value = false
  }
}

// 快速登录函数
const quickLogin = async (role: string) => {
  loading.value = true
  
  // 设置对应的用户名和密码
  const credentials = {
    admin: { username: 'admin', password: '123456' },
    user: { username: 'user', password: '123456' }
  }
  
  const loginData = credentials[role as keyof typeof credentials]
  
  try {
    // 调用后端登录API
    const response = await fetch('http://localhost:8080/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(loginData)
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      // 登录成功
      const responseData = result.data
      
      // 存储用户信息和token
      const userInfo = {
        id: responseData.userId,
        username: responseData.username,
        role: responseData.role,
        token: responseData.token,
        loginTime: new Date().toISOString()
      }
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      localStorage.setItem('token', responseData.token)
      
      ElMessage.success(`${role === 'admin' ? '管理员' : '用户'}登录成功！`)
      
      // 根据角色跳转到不同页面
      if (responseData.role === 'admin') {
        console.log('正在跳转到管理员页面...')
        await router.push('/admin/dashboard')
      } else {
        console.log('正在跳转到用户页面...')
        await router.push('/user/dashboard')
      }
    } else {
      ElMessage.error(result.message || '登录失败')
    }
  } catch (error) {
    console.error('快速登录请求失败:', error)
    ElMessage.error('网络连接失败，请检查后端服务是否启动')
  }
  
  loading.value = false
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  font-size: 28px;
  margin-bottom: 10px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form {
  margin-bottom: 20px;
}

.role-group {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.quick-login {
  margin-bottom: 20px;
  text-align: center;
}

.quick-login p {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #666;
}

.quick-login-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.login-tips {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 5px;
  font-size: 12px;
  color: #666;
  text-align: center;
}

.login-tips p {
  margin: 2px 0;
}
</style> 